
import styled from 'styled-components';
import React, { CSSProperties, useState, useEffect } from 'react';
import { Button, Modal, Select } from 'antd';
import { DatabaseOutlined } from '@ant-design/icons';

import { CategoryList } from '../list';
import { AddDataSourceDialog } from './add-data-source';

import { DataSource, dataSourceGetDataSources } from '../../services';

export interface DataSourceSelectProps {
    style?: CSSProperties;
    onChange: (dataSource: DataSource) => Promise<void>
}

export const DataSourceSelect: React.FC<DataSourceSelectProps> = (props) => {

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [data, setData] = useState<Array<DataSource>>([]);

    const [value, setValue] = useState<string>('');

    const refresh = async () => {
        let { data: dataSources } = await dataSourceGetDataSources(1, 1000);
        if (dataSources) {
            setData(dataSources);
            props.onChange(dataSources[0]);
            setValue('0');
        }
    }
    useEffect(() => {
        refresh();
    }, []);

    return (
        <Container style={props.style}>
            <Select
                style={{ flex: 1 }}
                value={value}
                onChange={(value) => {
                    setValue(value);
                    try {
                        let index = parseInt(value);
                        if (index >= 0 && index < data.length) {
                            props.onChange(data[index]);
                        }
                    } catch (err) {
                        console.log(err);
                    }
                }}
                options={data.map((item, index) => {
                    return {
                        value: index + '',
                        label: item.name
                    };
                })} />
            {
                <AddButton>
                    <Button
                        icon={<DatabaseOutlined />}
                        onClick={async () => {
                            setIsModalOpen(true);
                        }}
                    ></Button>
                </AddButton>
            }
            <Modal title="添加数据源" open={isModalOpen} onOk={() => {
                setIsModalOpen(false);
            }} onCancel={() => {
                setIsModalOpen(false);
            }}>
                <AddDataSourceDialog></AddDataSourceDialog>
            </Modal>
        </Container>
    );

}

const Container = styled.div`
    height: 45px;
    width: 100%;
    padding-left: 6px;
    display: flex;
    background-color: #EFEFEF;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #FFFFFF;
`;

const AddButton = styled.div`
    width: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
`;
